package com.katus.tileserver.controller;

import com.katus.tileserver.entity.Tile;
import com.katus.tileserver.service.TileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/tile")
public class TileController {
    double org_xy = 20037508.3427892;

    @Autowired
    TileService tileService;

    @GetMapping("/mvt/{sourceName}/{z}/{x}/{y}.mvt")
    public void getMvtTile(@PathVariable("sourceName") String tableName,
                           @PathVariable("x") Integer x, @PathVariable("y") Integer y, @PathVariable("z") Integer z,
                           HttpServletRequest request, HttpServletResponse response) throws IOException {
        Tile tile;
        if (z >= 6) {
            tile = tileService.getMvt2(tableName, tableName, x, y, z);
        } else {
//            System.out.println("**********-" + z + "-**********");
            tile = new Tile();
        }
        response.setContentType("application/x-protobuf");
//        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "1728000");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, Referer, User-Agent");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        OutputStream os = response.getOutputStream();
        IOUtils.write(tile.getImg(), os);
        response.setContentLength(tile.getImg().length);
        os.flush();
        os.close();
    }

    @RequestMapping(value = "/mr/{sourceName}/{z}/{x}/{y}", method = RequestMethod.GET)
    @ResponseBody
    public void getMrTile(@PathVariable("sourceName") Integer tableName, @PathVariable("z") Integer z, @PathVariable("x") Integer x, @PathVariable("y") Integer y, HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        try {
//            int y_i = (int) (Math.pow(2, z) - y);
//            y_i = y_i - 1;
            String rootPath = "/";
            String pngPath = String.format(rootPath + tableName + "/%d/%d/%d.png", z, x, y);
            FileInputStream inputStream = new FileInputStream(pngPath);
            byte[] bytes = readInputStream(inputStream);
            int filesize = bytes.length;

            response.setContentLength(filesize);
            response.setContentType(MediaType.IMAGE_PNG_VALUE);
            IOUtils.write(bytes, outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            byte[] msg = String.format("MR tiles [%d, %d, %d] not exists", z, x, y).getBytes();
            IOUtils.write(msg, outputStream);
            response.setContentLength(msg.length);
            response.setStatus(404);
        }
    }

    private static byte[] readInputStream(InputStream ins) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = ins.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        ins.close();
        return out.toByteArray();
    }
}

